package com.nowoe.server.util;

import com.nowoe.server.servlet.HttpServlet;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author 倚栏听风 2024/1/5 16:14
 */
public class XmlParser {
    public  static void parseXml(URL resource, Map<String, HttpServlet> servletMap) {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(resource);
            Element rootElement = document.getRootElement();
            List selectNodes = rootElement.selectNodes("//servlet");
            for (Object node : selectNodes) {
                if (node instanceof Element) {
                    Element element = (Element) node;
                    String servletName = element.selectSingleNode("servlet-name").getStringValue();
                    String className = element.selectSingleNode("servlet-class").getStringValue();
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    if (servletName != null && className != null) {
                        Class<?> clazz = Class.forName(className);
                        if (clazz.getSuperclass() == HttpServlet.class) {
                            servletMap.put(urlPattern, (HttpServlet) clazz.newInstance());
                        }
                    }
                }
            }
        } catch (DocumentException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

}
